//
//  LoginViewController.m
//  JiuLe
//
//  Created by xcq on 15/11/1.
//  Copyright © 2015年 Fine. All rights reserved.
//

#import "Common.h"
#import "JlUserManager.h"
#import <GTSDK/GeTuiSdk.h>
#import "LoginViewController.h"
#import "MessageViewController.h"
#import "HomeViewController.h"
#import "UnderlineButton.h"
#import "Balloon.h"
#import "ActivationViewController.h"
#import "ScanCodeViewController.h"
#import "BaseDataRequest.h"
#import "NSString+Check.h"
#import "NSString+Date.h"
#import "NSString+Check.h"
#import "ForgetPasswordViewController.h"
#import "BaseNavController.h"
typedef NS_ENUM(NSInteger, LoginType) {
    LoginTypeNormal = 0,
    LoginTypePhone ,
};

@interface LoginViewController() <UITextFieldDelegate> {
    CGFloat topConstant;
}
@property (weak, nonatomic) IBOutlet UIImageView *imageLog;
@property (weak, nonatomic) IBOutlet UIView *viewF;
@property (weak, nonatomic) IBOutlet UIView *viewT;
@property (weak, nonatomic) IBOutlet UIImageView *imageUser;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *passWord;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *btnScan;
@property (weak, nonatomic) IBOutlet UIButton *btnTourist;
@property (weak, nonatomic) IBOutlet UIButton *btnPhone;
@property (weak, nonatomic) IBOutlet UILabel *labPhone;
@property (weak, nonatomic) IBOutlet UnderlineButton *btnForget;
@property (weak, nonatomic) IBOutlet UIButton *btnYan;
@property (assign, nonatomic) LoginType loginType;
@property (strong, nonatomic) NSTimer *myTimer;
@property (assign, nonatomic) int time;
@end

#define kUserNameTag  0x22
#define kPassWordTag  0x21

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _userName.tag = kUserNameTag;
    _passWord.tag = kPassWordTag;
    _userName.delegate = self;
    _passWord.delegate = self;
    [self.view addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self
                                                                              action:@selector(touchesView)]];
    //绘制圆角边框
    [_btnYan.layer setMasksToBounds:YES];
    [_btnYan.layer setCornerRadius:3];
    [_btnYan.layer setBorderWidth:1.0];
    _btnYan.layer.borderColor=[UIColor whiteColor].CGColor;
    [self adaptation6];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    NSString *loginType = [[NSUserDefaults standardUserDefaults] objectForKey:UserLoginType];
    if (loginType != nil && ![loginType isEqualToString:@""] && loginType != NULL) {
        if ([loginType isEqualToString:@"normal"]) {
            self.loginType = LoginTypeNormal;
        }else{
            self.loginType = LoginTypePhone;
        }
    }else{
        self.loginType = LoginTypeNormal;
    }
    [_userName setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    [_passWord setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField.text.length > 0) {
        if (textField.tag == kPassWordTag) {
            _passWord.returnKeyType = UIReturnKeyJoin;
        }
        return YES;
    }
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == kUserNameTag) {
        if ([textField isFirstResponder]) {
            [_passWord becomeFirstResponder];
        }
    } else if (textField.tag == kPassWordTag) {
        if (textField.text.length > 0) {
            _passWord.returnKeyType = UIReturnKeyJoin;
            [self login:nil];
            return YES;
        }
        if ([textField isFirstResponder]) {
            _passWord.returnKeyType = UIReturnKeyNext;
            [_userName becomeFirstResponder];
        }
    }
    return YES;
}

- (void)touchesView {
    [self.view endEditing:YES];
}

#pragma mark - IBAction
- (IBAction)yanzhenm:(id)sender {
    if (_userName.text.length == 0) {
        TIPSFORVIEW(@"手机号不能为空！");
        return;
    }
    if (![_userName.text checkPhoneNumInput]) {
        TIPSFORVIEW(@"手机号格式不正确");
        return;
    }
    [SVProgressHUD showWithStatus:@"获取验证码.." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] getverificationCodePhone:self.userName.text withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            [self setTimer];
            [SVProgressHUD showSuccessWithStatus:@"验证码已发送!"];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}

- (IBAction)phoneLogin:(id)sender {
    if(_loginType == LoginTypeNormal){
        self.loginType = LoginTypePhone;
    }else if(_loginType == LoginTypePhone){
        self.loginType = LoginTypeNormal;
    }
}

- (IBAction)forgetAction:(id)sender {
    [self setForgetVCRootController];
}

- (IBAction)scanCodeLogin:(id)sender {
    //进入扫描登陆页面
    ScanCodeViewController *scanCode = getStoryOfControllerInstance(@"ScanCodeViewController");
    [self.navigationController pushViewController:scanCode animated:YES];
}

- (IBAction)touristLogin:(id)sender {
    [SVProgressHUD showSuccessWithStatus:@"登录成功!"];
    [NSUserDefaults setObject:@"" forKey:UserDataID];//UserDataID 为 @""代表游客
    [self performSelector:@selector(setRootController)
                   withObject:@{@"bol":@(YES)}
                   afterDelay:1.f];
}

- (IBAction)login:(id)sender {
    if (_loginType == LoginTypeNormal) {
        [self normalLongin];
         [NSUserDefaults setObject:@"normal" forKey:UserLoginType];
    }else{
        [self iphoneLogin];
        [NSUserDefaults setObject:@"phone" forKey:UserLoginType];
    }
}

#pragma mark - set/get
- (void)setLoginType:(LoginType)loginType{
    if (loginType == LoginTypeNormal) {
        _imageUser.image = [UIImage imageNamed:@"loginUser"];
        _btnForget.hidden = NO;
        _btnYan.hidden = YES;
        _userName.placeholder = @"用户名";
        _userName.keyboardType = UIKeyboardTypeDefault;
        _passWord.placeholder = @"密码";
        _passWord.keyboardType = UIKeyboardTypeDefault;
        [_btnPhone setImage:[UIImage imageNamed:@"login_phone"] forState:UIControlStateNormal];
        _labPhone.text  = @"手机登录";
        NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:UserDataName];
        NSString *passWord = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataPassWord];
        if (userName!=nil&&![userName isEqualToString:@""]) {
            _userName.text = userName;
        }
        if (passWord!=nil&&![passWord isEqualToString:@""]) {
            _passWord.text = passWord;
        }
        _loginType = LoginTypeNormal;
    }else{
        _imageUser.image = [UIImage imageNamed:@"icon_phone"];
        _userName.placeholder = @"手机号码";
        _userName.keyboardType = UIKeyboardTypePhonePad;
        _passWord.placeholder = @"手机验证码";
        _passWord.keyboardType = UIKeyboardTypeNumberPad;
        
        _btnForget.hidden = YES;
        _btnYan.hidden = NO;
        [_btnPhone setImage:[UIImage imageNamed:@"login_normal"] forState:UIControlStateNormal];
        _labPhone.text  = @"常规登录";
        NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:UserDataPhone];
        if (userName!=nil&&![userName isEqualToString:@""]) {
            _userName.text = userName;
        }else{
            _userName.text = @"";
        }
        _passWord.text = @"";
        _loginType = LoginTypePhone;
    }
}

#pragma mark - 私有方法
- (void)iphoneLogin{
    if (_userName.text.length == 0) {
        TIPSFORVIEW(@"手机号不能为空！");
        return;
    }
    if (![_userName.text checkPhoneNumInput]) {
        TIPSFORVIEW(@"手机号格式不正确");
        return;
    }
    if (_passWord.text.length == 0) {
        TIPSFORVIEW(@"密码不能为空！");
        return;
    }
    __weak LoginViewController *weakSelf = self;
    [SVProgressHUD showWithStatus:@"登录中.." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] loginUserPhone:self.userName.text verificationCode:self.passWord.text withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            NSDictionary *result = [responseObject objectForKey:@"result"];
            [NSUserDefaults setObject:[result objectForKey:@"token"] forKey:UserToken];
            NSInteger active = [[result objectForKey:@"is_active"] integerValue];
            [NSUserDefaults setObject:_userName.text forKey:UserDataPhone];
            [NSUserDefaults setObject:[result objectForKey:@"gender"]  forKey:UserSex];
            [NSUserDefaults setObject:[result objectForKey:@"height"]  forKey:UserHeight];
            [NSUserDefaults setObject:[result objectForKey:@"weight"]  forKey:UserWeight];
            [NSUserDefaults setObject:[result objectForKey:@"serial_number"] forKey:TerminalEquipment];
            if (active == 1) {//未激活
                Balloon *balloon = [[Balloon alloc] init];
                [balloon showTips:@"检查到您是新用户，即将进入激活页面"];
                [weakSelf performSelector:@selector(toActivation)
                               withObject:@{@"bol":@(YES)}
                               afterDelay:1.5f];
            }else{
                if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"push"] boolValue] == YES || [[NSUserDefaults standardUserDefaults] objectForKey:@"push"] == NULL) {
                    NSString *str = [NSString stringWithFormat:@"JL%@%@",[result objectForKey:@"serial_number"],[result objectForKey:@"user_id"]];
                    [GeTuiSdk bindAlias:[[NSString string] md5:str]];
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"push"];
                }
                [NSUserDefaults setObject:[result objectForKey:@"user_id"] forKey:UserDataID];
                [NSUserDefaults setObject:[result objectForKey:@"serial_number"] forKey:UserCCID];
                [[NSUserDefaults standardUserDefaults]setObject:[result objectForKey:@"ispush"] forKey:UserPush];
                NSString *activetime = [[NSString alloc] timeStamp:[result objectForKey:@"activetime"]];
                [NSUserDefaults setObject:activetime forKey:ActivationDate];
                [SVProgressHUD showSuccessWithStatus:@"登录成功!"];
                [weakSelf performSelector:@selector(setRootController)
                               withObject:@{@"bol":@(YES)}
                               afterDelay:1.f];
            }
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}

- (void)normalLongin{
    if (_userName.text.length == 0) {
        TIPSFORVIEW(@"用户名不能为空！");
        return;
    }
    if (![_userName.text checkUserName]) {
        TIPSFORVIEW(@"用户名只能为汉字·字母·数字");
        return;
    }
    if (_passWord.text.length == 0) {
        TIPSFORVIEW(@"密码不能为空！");
        return;
    }
    __weak LoginViewController *weakSelf = self;
    [SVProgressHUD showWithStatus:@"登录中.." maskType:SVProgressHUDMaskTypeClear];
    [[BaseDataRequest alloc] userLoginName:self.userName.text password:self.passWord.text withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            NSDictionary *result = [responseObject objectForKey:@"result"];
            [NSUserDefaults setObject:[result objectForKey:@"token"] forKey:UserToken];
            [NSUserDefaults setObject:_passWord.text forKey:UserDataPassWord];
            [NSUserDefaults setObject:_userName.text forKey:UserDataName];
            [NSUserDefaults setObject:[result objectForKey:@"gender"]  forKey:UserSex];
            [NSUserDefaults setObject:[result objectForKey:@"height"]  forKey:UserHeight];
            [NSUserDefaults setObject:[result objectForKey:@"weight"]  forKey:UserWeight];
            [NSUserDefaults setObject:[result objectForKey:@"serial_number"] forKey:TerminalEquipment];
            NSInteger active = [[result objectForKey:@"is_active"] integerValue];
            if (active == 1) {//未激活
                Balloon *balloon = [[Balloon alloc] init];
                [balloon showTips:@"检查到您是新用户，即将进入激活页面"];
                [weakSelf performSelector:@selector(toActivation)
                               withObject:@{@"bol":@(YES)}
                               afterDelay:1.5f];
            }else{
                if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"push"] boolValue] == YES || [[NSUserDefaults standardUserDefaults] objectForKey:@"push"] == NULL) {
                    NSString *str = [NSString stringWithFormat:@"JL%@%@",[result objectForKey:@"serial_number"],[result objectForKey:@"user_id"]];
                    [GeTuiSdk bindAlias:[[NSString string] md5:str]];
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"push"];
                }
                [NSUserDefaults setObject:[result objectForKey:@"user_id"] forKey:UserDataID];
                [NSUserDefaults setObject:[result objectForKey:@"serial_number"] forKey:UserCCID];
                [[NSUserDefaults standardUserDefaults]setObject:[result objectForKey:@"ispush"] forKey:UserPush];
                NSString *activetime = [[NSString alloc] timeStamp:[result objectForKey:@"activetime"]];
                [NSUserDefaults setObject:activetime forKey:ActivationDate];
                [SVProgressHUD showSuccessWithStatus:@"登录成功!"];
                [weakSelf performSelector:@selector(setRootController)
                               withObject:@{@"bol":@(YES)}
                               afterDelay:1.f];
            }
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}
- (void)setForgetVCRootController
{
    ForgetPasswordViewController *forget = [[UIStoryboard storyboardWithName:@"SCStoryboard" bundle:nil]instantiateViewControllerWithIdentifier:@"ForgetPasswordViewController"];
    [self.navigationController pushViewController:forget animated:YES];
}
- (void)setRootController {
    HomeViewController *home = [[HomeViewController alloc]initWithNibName:@"HomeViewController" bundle:nil];
    BaseNavController *baseNav = [[BaseNavController alloc] initWithRootViewController:home];
    [UIApplication sharedApplication].delegate.window.rootViewController    = baseNav;
}

- (void)toActivation{
    ActivationViewController *activation = [[UIStoryboard storyboardWithName:@"ActivationViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ActivationViewController"];
    activation.sequenceCode = self.userName.text;
    [self.navigationController pushViewController:activation animated:YES];
}

- (void)setTimer{
    self.time = 60;
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(scrollTimer) userInfo:nil repeats:YES];
    [_myTimer fire];
}

- (void)scrollTimer{
    if (self.time > 0) {
        --self.time ;
        _btnYan.enabled = NO;
        [_btnYan setTitle:[NSString stringWithFormat:@"%d 秒",self.time] forState:UIControlStateNormal];
    }else{
        self.time = 60;
        _btnYan.enabled = YES;
        [_btnYan setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_myTimer invalidate];
    }
}

- (void)adaptation6{
    if(SCREEN_HEIGHT > 568){
        [_imageLog setCenter:CGPointMake(_imageLog.center.x, _imageLog.center.y +50)];
         [_viewF setCenter:CGPointMake(_viewF.center.x, _viewF.center.y +70)];
         [_viewT setCenter:CGPointMake(_viewT.center.x, _viewT.center.y +80)];
    }
}

- (void)dealloc {
    removeObserver();
}

@end
